package top.zosoft.handler.adapter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author neal
 * @date 2023/12/26  17:05
 */
@Slf4j
@Component
public class MqttMessageAdapter extends SimpleChannelInboundHandler<MqttMessage> {
    private MqttMessageDelegate mqttMessageDelegate;

    // if the class has only one constructor, the parameters will be auto wired
    public MqttMessageAdapter(MqttMessageDelegate mqttMessageDelegate){
        this.mqttMessageDelegate = mqttMessageDelegate;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) {
        try {
            mqttMessageDelegate.process(ctx,msg);
        } catch (Exception e) {
            log.error("进栈数据异常:",e);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
        int port = address.getPort();
        String hostName = address.getHostName();
        if(evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            IdleState state = idleStateEvent.state();
            if(state==IdleState.READER_IDLE || state == IdleState.WRITER_IDLE || state == IdleState.ALL_IDLE){
                log.error("主机:{},端口:{}超时",hostName,port);
                //关闭通道
                ctx.channel().close();
            }
        }
    }
}
